package com.csii.adhoc.controller.dataReady;

import com.csii.adhoc.dataready.TMgnDir;
import com.csii.adhoc.dataready.TMgnDirPo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TreeConverter {
    public static List<TMgnDir> convertToTree(List<TMgnDir> nodeList) {
        Map<String, TMgnDir> nodeMap = new HashMap<>();

        // 将List中的节点转换为树形结构的节点对象，并存储到Map中
        for (TMgnDir node : nodeList) {
            nodeMap.put(node.getMenuId(), node);
        }

        // 递归地将节点添加到父节点的子节点列表中
        for (TMgnDir node : nodeList) {
            TMgnDir treeNode = nodeMap.get(node.getMenuId());
            TMgnDir parent = nodeMap.get(node.getParentId());
            if (parent != null) {
                if(parent.getChildren() == null) {
                    parent.setChildren(new ArrayList<>());
                }
                parent.getChildren().add(treeNode);
            }
        }

        // 找到根节点并返回
        List<TMgnDir> rootNodes = new ArrayList<>();
        for (TMgnDir node : nodeList) {
            if (node.getParentId().equals("0")) {
                rootNodes.add(nodeMap.get(node.getMenuId()));
            }
        }

        return rootNodes;
    }
}
